import React, { Component } from 'react'
import {
  View, Text, StyleSheet, Image, TouchableOpacity, ScrollView
} from 'react-native'

import NavBar from 'src/components/navBar'
import Divider from 'src/components/Divider'
import { showToast } from 'src/utils/ToastUtils'
import navigationhelper from 'src/components/navigationhelper'
import NameInput, { InputTypes } from 'src/components/Input/NameInput'
import { inject } from 'mobx-react/native'
import Layer from "src/components/Layer"

const countDownInitState = {
  countDown: 60,
  countText: '获取验证码',
  countColor: '#ff2121',
  isCountDown: false
}

@inject('cardManager', 'userAuth')
export default class MakePlanCodeView extends Component {

  constructor (props) {
    super(props)
    const plan = this.props.navigation.getParam('plan')
    const channel_bankcard_id = this.props.navigation.getParam('channel_bankcard_id')
    this.mounted = false
    this.countDownInterval = null
    this.state = {
      mobile: plan.bank_mobile,
      verifyCode: '',
      plan_id: plan.id,
      channel_bankcard_id: channel_bankcard_id,
      user_bankcards_id: plan.user_bankcards_id,
      channel: plan.channel,
      ...countDownInitState,
    }
  }

  componentDidMount () {
    Layer.hiddenLoading()
    this.mounted = true
    this.countDownInterval && clearInterval(this.countDownInterval)
    this.setState({ ...countDownInitState })
    this.countDownInterval = setInterval(this.handleCountDownTimer, 1000)
  }

  componentWillUnmount () {
    this.mounted = false
  }

  handleChangeText = (key) => (value) => {
    if (this.state[key] === value) return
    this.setState({ [key]: value })
  }

  handleStartCountDownTimer = () => {
    this.props.cardManager.authCard({
      token: this.props.userAuth.token,
      channel: this.state.channel,
      bank_card_id: this.state.user_bankcards_id
    }).then((res) => {
      this.setState({
        channel_bankcard_id: res.data
      })
      this.countDownInterval && clearInterval(this.countDownInterval)
      this.setState({ ...countDownInitState })
      this.countDownInterval = setInterval(this.handleCountDownTimer, 1000)
    })
  }

  handleCountDownTimer = () => {
    let { countDown } = this.state
    if (countDown === 1) {
      this.countDownInterval && clearInterval(this.countDownInterval)
      this.setState({ ...countDownInitState })
    } else {
      countDown--
      this.setState({
        countDown,
        countText: '倒计时' + countDown + 's',
        countColor: '#8e8e93',
        isCountDown: true
      })
    }
  }

  handleSubmit = () => {
    let { mobile, verifyCode } = this.state
    let message = ''
    if (!mobile) {
      message = '请输入银行卡预留手机号码'
    } else if (!verifyCode) {
      message = '请输入短信验证码'
    }
    if (message) {
      showToast({ text: message })
      return
    }
    Layer.showLoading()
    this.props.cardManager.authCardComfirm({
      token: this.props.userAuth.token,
      sms_code: verifyCode,
      plan_id: this.state.plan_id,
      channel_bankcard_id: this.state.channel_bankcard_id
    }).then((res) => {
      Layer.hiddenLoading()
      navigationhelper.navigate('MakePlanSuccessView', {
        reserve_amount: res.data.reserve_amount,
        bank_name: res.data.bank_name,
        card_number: res.data.card_number
      })
    }).catch(function(error){
      Layer.hiddenLoading()
      Layer.showMsg(error.message)
    })
  }

  renderGetVerifyCodeView = () => {
    let { isCountDown, countText, countColor } = this.state
    if (isCountDown) {
      return (
        <Text style={[styles.countDownStyle, { color: countColor }]}>
          {countText}
        </Text>
      )
    }
    return (
      <TouchableOpacity onPress={this.handleStartCountDownTimer}>
        <Text style={[styles.countDownStyle, { color: countColor }]}>
          {countText}
        </Text>
      </TouchableOpacity>
    )
  }

  render () {
    return (
      <View style={styles.container}>
        <NavBar 
            back={()=>{navigationhelper.goBack() }} 
            title={'短信授权'} 
            leftText={'返回'} 
            barStyle={'dark-content'}
            />
        <ScrollView
          bounces={false}
          style={{ flex: 1 }}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps={'handled'}>
          <View style={{ height: 16 }} />
          <View style={styles.contentContainer}>
            <NameInput
              showLeftText
              editable={false}
              hideClearImage
              leftText={'手机号码'}
              maxLength={11}
              text={this.state.mobile}
              keyboardType={'numeric'}
              inputType={InputTypes.PHONE}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入银行卡预留手机号码'}
              callback={this.handleChangeText('mobile')} />
            <Divider style={{ marginLeft: 16, marginRight: 16 }} />
            <NameInput
              showLeftText
              hideClearImage
              leftText={'验证码'}
              maxLength={6}
              keyboardType={'numeric'}
              leftTextStyle={styles.leftTextStyle}
              placeholder={'请输入短信验证码'}
              showRightView
              rightView={this.renderGetVerifyCodeView}
              callback={this.handleChangeText('verifyCode')} />
          </View>
          <View style={{ height: 16 }} />
          <View style={styles.messageContainer}>
            <Image style={styles.mesageIcon}
              source={require('src/assets/icon_message.png')} />
            <View style={{ width: 8 }} />
            <Text style={styles.messageText}>
              {'授权之后方可使用，若不授权则无法进行下一步操作'}
            </Text>
          </View>
        </ScrollView>
        <TouchableOpacity
          style={styles.btnContainer}
          onPress={this.handleSubmit}>
          <Text style={styles.btnText}>{'确定'}</Text>
        </TouchableOpacity>
        <View style={{ height: 16 }} />
      </View>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5'
  },
  contentContainer: {
    backgroundColor: 'white'
  },
  labelText: {
    fontSize: 20,
    color: '#2e2e2e',
    fontWeight: 'bold'
  },
  containerStyle: {
    height: 60,
    borderTopWidth: 0,
    borderLeftWidth: 0,
    borderRightWidth: 0,
    borderBottomWidth: 1,
    borderColor: '#378e93'
  },
  inputStyle: {
    paddingLeft: 0,
    paddingRight: 0,
    fontSize: 31,
    color: '#2e2e2e'
  },
  leftTextStyle: {
    width: 70,
    marginLeft: 16
  },
  countDownStyle: {
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 15
  },
  messageContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    minHeight: 35,
    paddingLeft: 13,
    paddingRight: 16,
    paddingTop: 9,
    paddingBottom: 9,
    marginLeft: 16,
    marginRight: 16,
    borderRadius: 5,
    backgroundColor: 'white'
  },
  messageIcon: {
    width: 18,
    height: 18,
    borderRadius: 9,
    marginRight: 8,
    resizeMode: 'contain'
  },
  messageText: {
    fontSize: 12,
    color: '#8e8e93'
  },
  btnContainer: {
    height: 50,
    marginLeft: 16,
    marginRight: 16,
    borderRadius: 5,
    backgroundColor: '#ff2121',
    alignItems: 'center',
    justifyContent: 'center'
  },
  btnText: {
    fontSize: 16,
    color: 'white',
    fontWeight: 'bold'
  }
})